package com.yuedou.api.controller.user;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yuedou.api.constant.ResponseCode;
import com.yuedou.api.controller.platform.BaseController;
import com.yuedou.api.entity.wxuser.User;
import com.yuedou.api.entity.wxuser.UserTransaction;
import com.yuedou.api.service.wxuser.UserService;
import com.yuedou.api.service.wxuser.UserTransactionService;
import com.yuedou.api.util.GsonResultBean;
import com.yuedou.api.util.Tools;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@Author: ZhouWei
 *@Description:  用户交易数据
 *@Date 2025-01-17
 */
@Component
@RestController
@RequestMapping("/user/transaction")//url:模块/资源/{}/细分
public class UserTransactionController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private UserTransactionService userTransactionService;


    /**我的优惠券列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            int offset = (pageIndex - 1) * pageSize;
            User user = userService.findById(user_id);
            //状态  0 - 未使用 1 - 已使用 2 - 已过期
            List<UserTransaction> list = userTransactionService.selectByUserId(user_id,user.getUserType(),offset,pageSize);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return result;
    }
}
